<template>
  <el-dialog
      v-model="isDialogShow"
      title="上传文件"
      width="30%"
      :before-close="handleClose"
      class="dia-box"
      close-on-press-escape
  >
    <div
        class="upload-box"
    >
      <el-form
          :model="uploadForm"
          label-width="6vw"
          :rules="uploadRules"
          ref="uploadFormRef"
          enctype="multipart/form-data"
          v-loading="loading"
      >
        <el-upload
            class="upload-demo"
            name="file"
            drag
            :action="actionURL"
            multiple
            style="height: 10%;width: 90%"
            v-model:file-list="uploadForm.file"
            :on-success="uploadSuccess"
            :limit="5"
            :auto-upload="false"
            :on-change="onchange"
            :on-progress="startUpload"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件至此处或<em>点击上传</em><br/>单次最多上传五个文件
          </div>
          <template #tip>
            <div class="el-upload__tip">
            </div>
          </template>
        </el-upload>
        <!--<el-form-item label="存储分类" prop="filCate">-->
        <el-form-item label="存储分类" >
          <el-input
              disabled
              v-model="nodeInfo.name"
              v-if="isInput"
          />
          <el-cascader
              :options="filesOptions"
              clearable
              v-model="uploadForm.fileCate"
              :props="props"
              @change="fileCateChange"
              v-else
              :show-all-levels="false"
              empty="请选择文件夹"
          />
          <el-select v-model="value" class="m-2" placeholder="请选择查看权限">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="last-btn">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitFileForm(uploadFormRef)">上传</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>


</template>

<script setup>
import {ElDialog, ElMessageBox, ElButton , ElIcon, ElUpload, ElFormItem, ElInput, ElCascader, ElForm, ElMessage, ElLoading, ElSelect } from "element-plus";
import {UploadFilled, Loading} from '@element-plus/icons-vue'
import {upload} from "@/api";
import {reactive, ref, onMounted} from "vue";
import axios from "axios";
import {getlist} from "@/api/index.js"
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import {baseurl} from "@/api/http"


const isDialogShow = ref(false)
const uploadFormRef = ref()
const arr = ref([])
//级联选择器分类数据
let filesOptions = ref([])
//默认上传表单
let uploadForm = reactive({
  file:[],
  fileCate:''
})
const uploadRules = reactive({
  fileName:[{ required: true, message: '文件名不能为空', trigger: 'blur' },],
  fileList:[{ required: true, message: '请上传文件', trigger: 'blur' },],
  filCate:[{ required: true, message: '分类不能为空', trigger: 'blur' },]
})
//从文件夹点击上传时传递的文件夹节点信息
let nodeInfo = reactive({
  name : '',
  key : '',
})
//判断上传选择分类时使用input还是级联
const isInput = ref(false)
const props = reactive({
    expandTrigger: "'hover' as const",
    value: 'listId',
    label: 'fileName',
    children: 'children',
    checkStrictly: true,
  }
)
const actionURL = ref(`${baseurl}/upload`)

//取消上传
const CancelToken = axios.CancelToken
let source = CancelToken.source();
window.source = null;
const router = useRouter()

//loading
let loading = ref(false)

//用户信息
let userInfo = ref([])

//权限等级选择
let options = ref([])
const value = ref('')


//vuex
const store = useStore()
onMounted(async ()=>{
  try {
    if(!localStorage.getItem('syhyDocManSys')){
      ElMessage({
        message:'请先登录',
        type:'error'
      })
      return router.push('/login')
    } else {
      let obj = JSON.parse(localStorage.getItem('syhyDocManSys'))
      userInfo.value.push(obj)
      //获取分类列表
      const {data:res} = await getlist({userId:obj.id})
      for (let i = obj.root; i<3; i++){
        options.value.push({
          value: i,
          label: `${i}级`,
        })
      }
    }
  } catch (e) {
    console.log(e)
  }
})
//自定义事件
const emits = defineEmits(['getFileLists'])

//开始上传的钩子，显示loading界面
const startUpload = ()=>{
  loading.value = true
}

//对话框显隐
const showDialog = async (node)=>{
  try {
    isDialogShow.value = true

    if(node){
      // console.log(node)
      nodeInfo.key = node.key
      nodeInfo.name = node.label
      isInput.value = true
      return
    } else {
      // console.log(uploadForm)
      isInput.value = false
      return
    }
  } catch (e) {
    console.log(e)
  }
}
// 关闭前回调
const handleClose = (done) => {
  // source.cancel()
  isDialogShow.value = false
  arr.value = []
  if(nodeInfo.key){
    nodeInfo.key = ''
    nodeInfo.name = ''
  }
  filesOptions = []
  uploadForm = {
    file:[],
    fileCate:''
  }
  source = CancelToken.source()
  done()
}
const fileCateChange = ()=>{}
// 上传文件发生变化时
const onchange = (file)=>{
  arr.value.push(file.raw)
}
// 提交表单
const submitFileForm = async ()=>{
  window.source = axios.CancelToken.source(); // 这里初始化source对象
  //表单判断校验
  if(!isInput){
    if(!uploadForm || uploadForm.file.length === 0 || uploadForm.fileCate === '' || value.value === '') {
      ElMessage({
        message:'请完整选择参数',
        type:'warning'
      })
      return
    }
  } else {
    if(uploadForm.file.length === 0) {
      ElMessage({
        message:'请选择上传文件',
        type:'warning'
      })
      return
    } else if( value.value === ''){
      ElMessage({
        message:'请选择权限等级',
        type:'warning'
      })
      return
    }
  }
  //判断所属文件夹
  let list
  //若从文件夹上传，文件夹节点为node，若从upload组件直接上传，文件夹节点是表单fileCate
  if(isInput.value){
    list = nodeInfo.key
  } else {
    list = uploadForm.fileCate
  }
  // console.log(arr.value,list,store.state.userInfo.username)
  //一个一个上传
  for (let i = 0; i < arr.value.length; i++) {
    loading.value = true
    //手动添加表单，将文件追加到表单里
    let fd = new FormData();
    fd.append('file', arr.value[i])
    fd.append('fileCate', list)
    fd.append('uploader', userInfo.value[0].username)
    fd.append('root', userInfo.value[0].root)
    axios({     //上传服务器接口
      // url: 'http://192.168.10.100:8000/upload',       //上传服务器接口
      url: actionURL.value,       //上传服务器接口
      method: 'post',
      data: fd,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    },  {
      cancelToken: window.source.token
    }).then((res) => {
      if(res.data.code === 200){
        // cancel = ''
        loading.value = false
        ElMessage({
          message: '上传成功!',
          type: 'success',
        })
        isDialogShow.value = false
        arr.value = []
        uploadForm = {
          file:[],
          fileCate:''
        }
        //刷新文件列表
        emits('getFileLists',{key:list})
      } else {
        // cancel = ''
        loading.value = false
        ElMessage({
          message: '上传失败!',
          type: 'warning',
        })
        isDialogShow.value = false
        arr.value = []
        uploadForm = {
          file:[],
          fileCate:''
        }
      }
    }).catch(error => {
      if (axios.isCancel(error)) {
        alert('取消')
        console.log('请求已被取消', error.message);
      } else {
        console.log('请求发生错误', error.message);
      }
    })
  }
}
const down = async ()=>{
  const {data:res} = await upload()
}
const uploadSuccess = (res,uploadFile,uploadFiles)=>{
  loading.value = false
}
defineExpose({isDialogShow,showDialog})
</script>

<style scoped lang="less">
.dia-box{
  z-index: 999;
  height: 50vh;
  width: 20vw;
  .upload-box{
    /deep/.el-form-item {
      margin-top: 2vh;
    }
    .upload-demo{
      /deep/.el-upload.is-drag {
        display: block;
        margin-top: -2vh;
      }
      margin: 0 auto;
      /deep/.el-upload-dragger .el-upload__text {
        color: var(--el-text-color-regular);
        font-size: 1vh;
        text-align: center;
        margin: -8px 0;
      }
      /deep/.el-upload-dragger{
        height: 10vh;
      }
      /deep/.el-upload-dragger .el-icon--upload{
        font-size: 4vh;
        margin-top: 1.5vh;
      }
      /deep/.el-upload-dragger{
        padding: 0;
        height: 11vh;
        margin-bottom: 3vh;
        /deep/.el-upload-dragger .el-icon--upload {
          font-size: 3vh;
          color: var(--el-text-color-placeholder);
          margin: 0 !important;
        }
        /deep/.el-upload-dragger .el-upload__text {
          color: var(--el-text-color-regular);
          font-size: 1.5vh !important;
          text-align: center;
        }
        /deep/.el-input {
          width: 82%;
        }
        /deep/.el-form-item__content {
          width: 70%;
        }
        /deep/.el-button {
          margin-left: 5vw;
          margin-top: 2vh;
        }
        /deep/.el-upload-list__item .el-upload-list__item-info {
          margin-bottom: 0.5vh;
        }
      }
      .last-btn{

      }
    }
  }
}
/deep/body {
  width: 100vw !important;
}

/deep/.el-input{
  width: 70% !important;
}
.m-2{
  margin-top: 1.5vh;
}
</style>
